<?php
/**
 * Created by PhpStorm.
 * User: dx
 * Date: 16/5/5
 * Time: 下午3:09
 */
$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();

$process_lock_file = '/data/anhui/api/app/storage/logs/coupons_activity.lock';

if(file_exists($process_lock_file)){
    echo date('Y-m-d H:i:s',time())." coupons activity check cancel locked \n";
    exit(-1);
}else{
    touch($process_lock_file);
    echo date('Y-m-d H:i:s',time())." coupons activity check cancel started \n";

    //开始生成券巴拉巴拉
    $coupons_temp_table = DB::table('coupons_temp_table')
        ->where('status',1)
        ->select('count','created_by','code_type','coupon_base_info_id','code','id')
        ->first();
    if($coupons_temp_table){
        $input = array(
            'coupon_base_info_id'   => $coupons_temp_table->coupon_base_info_id,
            'status'       => 1,
            'received_user_id' => 0,
            'used_user_id'      => 0,
            'created_at' => date('Y-m-d H:i:s',time()),
            'updated_at' => date('Y-m-d H:i:s',time()),
        );

        $num = intval($coupons_temp_table->count);
        $limit = 5000;
        $bag = array();
        for ($i = 0, $j = 0; $i < $num; $i++){
            //生成统一的优惠码
            if($coupons_temp_table->code_type == 1){ //1 代表 随机码
                $bonus_arr = Helper::getStr($coupons_temp_table->coupon_base_info_id,$coupons_temp_table->created_by);
                $bonus_sn = $bonus_arr['str_num'];
            }else{
                $bonus_sn = $coupons_temp_table->code;
            }
            $input['code'] = $bonus_sn;

            $count = count($bag);
            if ( $count === $limit OR $count === ($num - 1) )
            {
                if($num - 1 != 0){
                    DB::table('coupons')->insert($bag);
                }
                $bag = array();
            }
            $bag[] = $input;
            $j++;
        }

        if ( count($bag) > 0 )
        {
            DB::table('coupons')->insert($bag);
            $bag = array();
        }
        DB::update("update coupons_temp_table set status = 0 where id=? limit 1", array($coupons_temp_table->id));
        Log::info("优惠券生成完毕");
    }

    echo date('Y-m-d H:i:s',time())." coupons activity check retry stoped \n";
    unlink($process_lock_file);

}
